//
//  QZAddressViewController.m
//  SmallShoppingCenter
//
//  Created by 上官惠阳 on 15/10/15.
//  Copyright © 2015年 上官惠阳. All rights reserved.
//

#import "QZAddressViewController.h"
#import "QZForgetAndRegistCell.h"
#import "QZKeepView.h"
#import "QZCountyVc.h"
#import "QZAddressModel.h"
#import "QZAddressInfo.h"

@interface QZAddressViewController ()<UITextFieldDelegate>

@end

@implementation QZAddressViewController
{
    NSArray *pArr;
    NSArray *_changeArray;
    UIView *_grayView;
    QZKeepView *_keepView;
    
    NSString *_name;
    NSString *_phoneNumber;
    NSString *_region;//区域
    NSString *_postcode;//邮政编码
    NSString *_detailedAddress;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"新增地址";
    
    [self addBtnOnNavWithTitle:@"地址" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];
    
    [self addBtnOnNavWithTitle:@"保存" andImageName:nil andTarget:self andAction:@selector(keepAction) andFrame:CGRectMake(0, 0, 40, 20) andDirection:right];
    
    [self createTableViewWithPlainStyle:NO andSeparatorStyleNone:NO andBackGroudImageName:nil];
    
    [self registCellWithNib:@"QZForgetAndRegistCell" addIdentifier:@"cell" addHeight:44];
    
    [self loadData];
    
    
    [self createGrayView];
    [self createKeepView];
    
    [self changeAddress];//修改地址跳过来的话
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAddressText:) name:@"添加地址" object:nil];
 
}
-(void)changeAddress{
    if (self.addressModel) {
        _name = self.addressModel.receiver;
        _phoneNumber = self.addressModel.tel;
        _postcode = [NSString stringWithFormat:@"%ld",self.addressModel.zipCode];
        _detailedAddress = self.addressModel.address;
    }

    
    
}
- (void)addAddressText:(NSNotification *)noti{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    
    QZForgetAndRegistCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    _region = [noti object];
    cell.rightFiled.text = [noti object];

    
}

-(void)tableViewTap{
    
    [self.view endEditing:YES];
    
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)keepAction
{
    
    if (![self isMobileNumber:_phoneNumber]) {
        [[iToast makeText:@"请输入正确的号码"] show];
    }else{
        
        if (_name && _region && _postcode && _detailedAddress) {

            
            [self addAddresssInfo];

        }else{
            [[iToast makeText:@"信息填写不完全"] show];
        }

    }

}

- (void)addAddresssInfo{
    NSDictionary *addressID = [[QZAddressInfo shared] showAddressInfo];
    
    //修改收货地址
    if (self.addressModel) {
        NSDictionary *diction = [[QZAddressInfo shared] showAddressInfo];
        NSString *address = [NSString stringWithFormat:@"%@%@%@%@",diction[@"sheng"],diction[@"shi"],diction[@"qu"],diction[@"jie"]];
        
        NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetAddressSet"];
        NSDictionary *dic = @{
                              @"addressbie":address,
                              @"receiver":_name,
                              @"tel":@([_phoneNumber integerValue]),
                              @"address":_detailedAddress,
                              @"zipCode":@([_postcode integerValue]),
                              @"province_id":addressID[@"shengID"],
                              @"city_id":addressID[@"shiID"],
                              @"district_id":addressID[@"quID"],
                              @"street_id":addressID[@"jieID"],
                              @"address_id":@(self.addressModel.id)
                              };
        
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"添加收货地址" stopRequest:YES isSerializer:NO isCache:NO];
    return;
    }
    //添加收货地址
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetAddressAdd"];
    NSDictionary *dic = @{
                          @"user_id":@([[QZUserInfo userId] integerValue]),
                          @"receiver":_name,
                          @"tel":@([_phoneNumber integerValue]),
                          @"address":_detailedAddress,
                          @"zipCode":@([_postcode integerValue]),
                          @"province_id":addressID[@"shengID"],
                          @"city_id":addressID[@"shiID"],
                          @"district_id":addressID[@"quID"],
                          @"street_id":addressID[@"jieID"],
                          };
    
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"添加收货地址" stopRequest:YES isSerializer:NO isCache:NO];

}



//判断是否为正确的电话号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * MOBILE = @"^1[3|4|5|7|8]\\d{9}$";//手机号
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";//大陆地区固话及小灵通
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestphs evaluateWithObject:mobileNum] == YES)){
        return YES;
    }else{
        return NO;
    }
}
-(void)createGrayView
{
    UIView *grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    grayView.backgroundColor = [UIColor blackColor];
    grayView.alpha = 0.5;
    grayView.hidden = YES;
    [self.view addSubview:grayView];
    _grayView = grayView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_grayView addGestureRecognizer:tap];
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    _grayView.hidden = YES;
    _keepView.hidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)createKeepView
{
    _keepView = [[[NSBundle mainBundle]loadNibNamed:@"QZKeepView" owner:self options:nil]lastObject];
    _keepView.frame = CGRectMake(0, 115 + 64, WIDTH, 125);
    _keepView.hidden = YES;
    [self.view addSubview:_keepView];
}
-(void)loadData
{
    [self.tableSource addObject:@[@"收件人",@"电话号码",@"区域选择",@"邮政编码",@"详细地址"]];
    pArr = @[@"名字",@"11位手机号",@"地区信息",@"邮政编码",@"街道门牌信息"];
    if (self.addressModel) {
        NSString *zipCode = [NSString stringWithFormat:@"%ld",_addressModel.zipCode];
        _changeArray = @[_addressModel.receiver,_addressModel.tel,@"",zipCode,_addressModel.address];
    }
    
    [self.tableView reloadData];
}

#pragma mark tableVeiw delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(void)loadCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    QZForgetAndRegistCell *forCell = (QZForgetAndRegistCell *)cell;
    forCell.rightFiled.font = [UIFont systemFontOfSize:14];
    forCell.leftName.text = self.tableSource[indexPath.section][indexPath.row];
    forCell.rightFiled.placeholder = pArr[indexPath.row];
    
    if (self.addressModel) {
        forCell.rightFiled.text = _changeArray[indexPath.row];
    }
    
    if (indexPath.row == 2) {
        forCell.rightFiled.userInteractionEnabled = NO;
        forCell.userInteractionEnabled = YES;
        forCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    
    forCell.rightFiled.delegate = self;
    
    forCell.rightFiled.tag = indexPath.row+100;
    [forCell.rightFiled addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    
}


-(void)actionAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    if (indexPath.row == 2) {
        QZCountyVc *countryVC = [[QZCountyVc alloc] init];
        countryVC.isAddAddress = YES;
        [self.navigationController pushViewController:countryVC animated:YES];
        
    }
}
-(void)textChange:(UITextField *)textField{
    NSInteger index = textField.tag - 100;
    switch (index) {
        case 0:
            _name = textField.text;
            break;
        case 1:
            _phoneNumber = textField.text;
            break;
        case 2:
            _region = textField.text;
            break;
        case 3:
            _postcode = textField.text;
            break;
        case 4:
            _detailedAddress = textField.text;
            break;
        default:
            break;
    }
    
    
}


#pragma mark textFiled delegate

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    
}

-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    
    if ([tag isEqualToString:@"添加收货地址"]) {
        
        if ([value[@"data"][@"status"] integerValue] == 100) {
//            if ([[TMCache sharedCache] objectForKey:@"defuAddress"]) {
//
//                NSDictionary *diction = [[QZAddressInfo shared] showAddressInfo];
//                NSString *address = [NSString stringWithFormat:@"%@%@%@%@",diction[@"sheng"],diction[@"shi"],diction[@"qu"],diction[@"jie"]];
//                QZAddressModel *model = [[QZAddressModel alloc] init];
//                model.receiver = _name;
//                model.tel = _phoneNumber;
//                model.address = _detailedAddress;
//                model.zipCode = [_postcode integerValue];
//                model.province_id = [diction[@"shengID"] integerValue];
//                model.city_id = [diction[@"shiID"] integerValue];
//                model.district_id = [diction[@"quID"] integerValue];
//                model.street_id = [diction[@"jieID"] integerValue];
//                model.addressbie = address;
//                model.id =[value[@"data"][@"data"][@"id"] integerValue];
//                
//                [[TMCache sharedCache] setObject:model forKey:@"defuAddress"];
//            }
                _grayView.hidden = NO;
                _keepView.hidden = NO;
            
            }else{
                NSLog(@"%@",value);
            }

        }
    
}


@end
